<template>
  <div class="file_main">
    <div class="file_head">
      <div class="file_head_left" style="float:left;">
        <a-upload
          class="upload_but"
          name="file"
          :multiple="true"
          :data="uploadData"
          :action="uploadFile()"
          :headers="headers"
          @change="handleAvatarSuccess"
          :showUploadList="false"
        >
          <a-button type="primary">
            <a-icon type="upload"/>
            上传
          </a-button>
        </a-upload>
        <a-button
          @click="downloadFile"
          :disabled="isDirDisable"
        >
          <a-icon type="download"/>
          下载
        </a-button>
      </div>
      <div class="file_head_right" style="margin-left: 60vw;"></div>
      <br/><br/>
      <a-divider/>
    </div>
    <div class="table">
      <a-table
        class="filesTable"
        :data-source="fileList"
        :pagination="false"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange
        }"
      >
        <a-table-column key="name" title="文件名称" data-index="name" v-loading="fileLoading">
          <template slot-scope="name">
            <span>
              <a-icon class="file_ico" :type="checkType(name)"/>
              <a-button type="link"
                        @click="clickFile(name)"
              >{{ formatName(name) }}</a-button>
            </span>
          </template>
        </a-table-column>
        <a-table-column key="size" title="文件大小" data-index="size">
          <template slot-scope="size">
            {{ updataFileSize(size) }}
          </template>
        </a-table-column>
        <a-table-column
          key="lastModified"
          title="修改时间"
          data-index="lastModified"
        >
          <template slot-scope="lastModified">
            <span>{{ timestampToTime(lastModified) }}</span>
          </template>
        </a-table-column>
      </a-table>
    </div>
    <el-dialog
      title="预览"
      class="preView_diaglog"
      :visible.sync="preViewVisible"
      width="50%"
      top="5vh"
      :close-on-click-modal="false"
    >
      <a-textarea
        :disabled="true"
        v-if="preViewType == 'txt'"
        v-model="preViewText"
        :auto-size="{ minRows: 18 }"
        style="color: #000;background-color: #fff;height: 60vh;"
      />
      <img :src="previewSrc" v-if="preViewType == 'img'"/>
    </el-dialog>
  </div>
</template>
<script>
import Axios from "axios"
import {formatName, lastPath} from "../../api/utils/fileFormat"
import {baseUrl} from "../../api/baseUrl"
import {openWindow} from "../../api/utils/window"

export default {
  name: "files",
  props: ["fileType", "uploadList", "isRecycle"],
  data() {
    let id
    if (this.$route.query.storeHouseId){
      id = this.$route.query.storeHouseId
    }else id = 0
    console.log(this.$route.query.storeHouseId)
    let path = "" // 实际按实际情况获取当前文件路径
    return {
      pathList: [],
      id: id,
      path: path,
      localPath: "user_space/" + id + "/" + path,
      currentPath: "user_space/" + id + "/" + path,
      fileLoading: false,
      fileList: [],
      imageUrl: "",
      dialogImageUrl: "",
      reName:false,
      isReNameDisable:true,
      dialogVisible: false,
      preViewVisible: false,
      previewSrc: "",
      preViewType: "txt",
      preViewText: "",
      isDirDisable: false,
      skeleton_loading: false,
      share_loading: false,
      shareFileDialogVisible: false,
      shareIsPrivate: true,
      selectedRowKeys: [],
      userId: localStorage.getItem("userId"),
      dirName: "",
      headers: {
        token: localStorage.getItem("token")
      },
      uploadData: {
        path: ""
      },
      shareType: "private",
      shareKey: "",
      sharePwd: ""
    }
  },
  created() {
    this.pathList[0] = this.id
    this.getFiles()
  },
  watch: {
    selectedRowKeys(val) {
      /**
       * 如果目标文件是文件夹，那么将无法分享、移动、下载。
       */
      this.isReNameDisable = true
      this.isDirDisable = false
      for (let item of val) {
        if (this.fileList[item].name[this.fileList[item].name.length - 1] == "/") {
          this.isReNameDisable = true
          this.isDirDisable = true
        }else{
          this.isReNameDisable = false
        }
      }
      if (val.length>1) this.isReNameDisable = true
    },
  },
  mounted() {

    this.uploadData.path = "/"
  },
  methods: {
    uploadFile() {
      return `${baseUrl}/oss/upload?id=`+this.id+`&&path=` + this.path
    },
    formatName(name) {
      return formatName(name)
    },
    getFiles() {
      this.fileLoading = true
      const _this = this
      let form = {
        "id": this.id,
        "path": this.path
      }
      if (form.path.length > 0 && form.path[form.path.length - 1] != "/") {
        form.path = form.path + "/"
      }
      if (form.path.length > 0 && form.path[0] == "/") {
        for (let i = 1; i < form.path.length; i++) {
          form.path[i - 1] = form.path[i]
        }
      }
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      this.$http.oss.getFileList(form).then(function (resp) {
        _this.fileList = []
        let fileList = []
        for (let item of resp) {
          if (item.name != _this.currentPath + "/") {
            _this.fileList.push(item)
          }
        }
        setTimeout(() => {
          loading.close();
        }, 250);
        _this.fileLoading = false
      })
    },
    getFileFormatList(format) {
      // req.getFileFormatList(format).then(res => {
      //   this.setFileList(res.data)
      // })
    },
    setFileList(data) {
      this.fileList = []

      if (data.length == 0) {
        return
      }
      let index = this.userId.length + 12
      for (let i = 1; i < this.path.length; i++) {
        index += this.path[i].length + 1
      }
      let file_arr = []
      data.forEach(element => {
        if (element.size == 0) {
          return
        }
        element.name = element.name.substr(index)
        // 为了保证文件列表中文件夹在文件上面，优先将「文件夹」push进文件列表。
        if (element.name.charAt(element.name.length - 1) == "/") {
          this.fileList.push(element)
          return
        }
        file_arr.push(element)
      })
      this.fileList = this.fileList.concat(file_arr)
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    timestampToTime(timestamp) {
      if (timestamp == null) {
        return ""
      }
      let date = new Date(timestamp)
      let Y = date.getFullYear() + "-"
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-"
      let D = date.getDate() + " "
      let h = date.getHours() + ":"
      let m = date.getMinutes()
      return Y + M + D + h + m
    },
    clickBreadcrumb(item, index) {
      let list = []
      for (let i = 0; i <= index; i++) {
        list.push(this.pathList[i])
      }
      this.pathList = list
      this.path = ""
      if (index > 0) {
        this.currentPath = ""
        for (let i = 1; i <= index; i++) {
          this.path = this.path + this.pathList[i] + "/"
        }
        this.currentPath =  "user_space/" + this.id + "/" + this.path
      }
      const _this = this
      let form = {
        "id": this.id,
        "path": this.path
      }
      this.$http.oss.getFileList(form).then(result => {
        this.fileList = result
      })
    },
    checkType(name) {
      if (name.charAt(name.length - 1) == "/") {
        return "folder"
      }
      switch (name.substr(name.indexOf(".") + 1)) {
        case "txt":
          return "file-text"
          break
        case "pdf":
          return "file-pdf"
          break
        case "png":
          return "file-image"
          break
        case "jpg":
          return "file-image"
          break
        case "jpeg":
          return "file-image"
          break
        case "gif":
          return "file-image"
          break

        default:
          return "file"
          break
      }
    },
    clickFile(path) {
      if (path[path.length - 1] == "/") {
        this.path = this.path + formatName(path) + "/"
        this.pathList.push(formatName(path))
        this.currentPath = "user_space/" + this.id + "/" + this.path
        this.getFiles()
      } else {
        let json = {
          "path": path
        }
        this.$http.oss.previewFile(json).then(function (resp) {
          openWindow(resp.data.fileUrl, path, 1500, 750)
        })
      }
    },
    clickDir(name) {
      // 当点击的是文件夹时
      this.path.push(name.substr(0, name.length - 1))
      // 清空当前选中的文件。
      this.selectedRowKeys = []
    },
    handleAvatarSuccess() {
      this.$notify({
        title: "上传成功",
        type: "success"
      })
      this.getFiles()
    },
    downloadFile() {
      if (this.selectedRowKeys.length > 1) {
        this.$notify({
          title: "请选择单个文件下载",
          type: "error"
        })
      } else {
        for (let item of this.selectedRowKeys) {
          let form = {//补全form
            userId: "",
            teamId: "",
            storeHouseId: "",
            fileName: "",
            filePath: "",
            download: 1,
            size: this.fileList[item].size,
          }
          this.$http.record.save(form)
          window.open(baseUrl + "/oss/downloadFile?fileName=" + this.fileList[item].name)
        }
      }
    },
    downloadFile_fun(fileJson) {
      // utils.downloadFile(fileJson)
    },
    shareTypeChange(e) {
      this.shareType = e.target.value
      if (this.shareType == "private") {
        this.shareIsPrivate = true
      } else {
        this.shareIsPrivate = false
      }
      this.shareFile_fun()
    },
    updataFileSize(size) {
      if (size == null) {
        return "-"
      }
      let size_ = "0"
      let type = "B"
      if (size < 1000) {
        size_ = size
      } else if (size > 1000 && size < 1000000) {
        size_ = size / 1000
        type = "K"
      } else {
        size_ = size / 1000000
        type = "M"
      }
      return Math.round(size_ * 10) / 10 + type
    }
  }
}
</script>

<style>
.filesTable {
  margin-top: 15px;
}

.breadcrumb_but {
  margin: 0px;
  padding: 0px;
}

.ant-btn-link {
  color: black;
}

.upload_but {
  margin-left: 10px;
  /* float: left; */
  margin-right: 5px;
}

.file_ico {
  position: relative;
  top: 3px;
  font-size: 1.5rem;
}

.moveFile_but {
  margin-top: 15px;
  margin-right: 5px;
  width: 150px;
}

.ant-page-header {
  border: 0px;
}

.ant-btn-link {
  color: black;
}

.ant-divider-horizontal {
  margin: 10px 0px;
}

.share_input {
  margin-top: 10px;
  max-width: 200px;
}

.share_input_pwd {
  margin-top: 10px;
  max-width: 100px;
}

.ant-table-body {
  max-height: 70vh;
  overflow: auto;
}

.preView_diaglog .el-dialog__body {
  padding: 0px;
}

.preView_diaglog .el-dialog__body iframe {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid #606266;
}

.preView_diaglog .el-dialog__body img {
  width: 100%;
}
</style>
